﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.GridType;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Common.Menus;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Linq;

namespace SmartCity.BasicData.Api.Application.Handler.GridType
{
    /// <summary>
    /// 获取网格类型列表的中介者处理类
    /// </summary>
    public class GetGridTypeListHandler : IRequestHandler<GetGridTypeCommand, ApiResult<IList<GridTypeListDTO>>>
    {
        private readonly IBaseRepository<GridTypeModel> gridTypeRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 获取网格类型列表的中介者处理方法
        /// </summary>
        /// <param name="gridTypeRepo">网格类型的仓储对象</param>
        /// <param name="mapper">automapper 的映射对象</param>
        public GetGridTypeListHandler(IBaseRepository<GridTypeModel> gridTypeRepo, IMapper mapper)
        {
            this.gridTypeRepo = gridTypeRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 中介者处理类的具体处理方法
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消参数</param>
        /// <returns></returns>
        public Task<ApiResult<IList<GridTypeListDTO>>> Handle(GetGridTypeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<IList<GridTypeListDTO>> result = new ApiResult<IList<GridTypeListDTO>>();

            //var gridtypes = new List<GridTypeModel>(); //网格类型根据条件查出来
            //if (!string.IsNullOrEmpty(request.GridTypeName))
            //{ //如果request参数里网格类型名称不为空,查询时带上这个条件
            //    gridtypes = gridTypeRepo.GetAsync(x => x.GridTypeName.Contains(request.GridTypeName)).Result;
            //}
            //else {
            //    gridtypes = gridTypeRepo.GetAllAsync().Result;
            //}

            var gridtypes = gridTypeRepo.QueryAllAsync().Result.Where(x => x.IsDeleted == false);//表达式 select * from t where t.IsDeleted =false

            if (!string.IsNullOrEmpty(request.GridTypeName))//判断要不要查询GridTypeName 网格类型名称
            {
                gridtypes = gridtypes.Where(x => x.GridTypeName.Contains(request.GridTypeName)); //select * from t where t.IsDeleted =false and GridTypeName like '%request.GridTypeName%'
            }
            if (!string.IsNullOrEmpty(request.GridTypeCategory))// 判断要不要查询分类
            {
                gridtypes = gridtypes.Where(x => x.GridTypeCategory == request.GridTypeCategory);//select * from t where t.IsDeleted =false and GridTypeName like '%request.GridTypeName%'
            }

            result.Code = EnumResultCode.Success;
            result.Msg = "查询网格类型成功!";
            result.Data = mapper.Map<IList<GridTypeListDTO>>(gridtypes.ToList());


            return Task.FromResult(result);
        }
    }
}
